/*
 * @Author: yangzonglong
 * @Date: 2021-03-05 12:08:36
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-16 16:39:29
 * @Auditor:
 */
import React, { useMemo, useState, useEffect, useRef } from 'react';
import { DatePicker } from 'antd';
import { FormItemProps } from 'antd/lib/form';
import { DatePickerProps as AndtdDatePickerProps } from 'antd/lib/date-picker';
import moment from 'moment';

export interface DatePickerProps extends Record<string, any> {
  formItemProps?: FormItemProps;
  datePickerProps?: AndtdDatePickerProps;
  readOnly?: boolean;
  disabled?: boolean;
}

const App = (props: DatePickerProps) => {
  const isChanged = useRef(false);
  const { disabled, onChange, value, options } = props;
  const [clear, setClear] = useState(false);
  const setInitValueTimer = useRef<any>(null);

  useEffect(() => {
    if (setInitValueTimer.current) {
      clearTimeout(setInitValueTimer.current);
      setInitValueTimer.current = null;
    }

    setInitValueTimer.current = setTimeout(() => {
      if (isChanged.current || value || value === '' || value === null) return;

      onChange(options.isInitialValue ? moment().format(options?.format) : undefined, true);
      isChanged.current = true;
    }, 100);
  }, [value, onChange, options]);

  const _value = useMemo(() => {
    if (clear) return undefined;
    if (value === null || value === '') return undefined;
    return value ? moment(value) : null;
  }, [value, clear]);

  const showTime = useMemo(() => {
    return { showTime: options?.format?.includes(':mm:') };
  }, [options?.format]);

  return <DatePicker size='small' {...showTime} disabled={disabled} {...props.options} value={_value} onChange={(e) => {
    onChange(e ? moment(e).format(options?.format) : '');
    setClear(!e);
  }} />;
};

export default App;
